import Taro from "@tarojs/taro";
import Toast from '@/hooks/useToast'
import { BASE_URL, HTTP_RESPONSE } from "../const"
import { ApiOptions } from '@/types/index'
import { useDispatch } from "@/hooks/useStore"

/**
 * qpi请求
 * @param url string
 * @param params object
 * @param method string
 * @param options ApiOptions
 */
const httpRequest = function (url: string, params: object, method: any, options: ApiOptions) {
    let { showToast = false,loading = false, title ='加载中' } = options
    const token = Taro.getStorageSync('token')
    if (loading) Toast.loading(title);
    return new Promise<{}>((resolve, reject) => {
        Taro.request({
            url: BASE_URL + url,
            data: params,
            method: method,
            header: {
                'content-type': 'application/json',
                'Authorization': token.accessToken ? token.accessToken : '',
            }
        }).then(async (res) => {
            const { statusCode, data } = res;
            if (loading) Toast.hide()
            switch (statusCode) {
                case HTTP_RESPONSE.SUCCESS:
                    const result = data[HTTP_RESPONSE.RESULT_FIELD]
                    if (showToast){
                        if (result.type==='success'){
                            Toast.success(result.message)
                        }else if (result.type==='warning'){
                            Toast.warn(result.message)
                        }else{
                            Toast.error(result.message)
                        }
                    }
                    return resolve(result)
                case HTTP_RESPONSE.AUTHENTICATE:
                    Toast.warn("登陆授权已失效!请重新授权登陆.!")
                    await useDispatch('clearUserInfo');
                    return reject(data)
                case HTTP_RESPONSE.NOT_FOUND:
                    Toast.error("当前请求资源路径不存在!")
                    return reject(data)
                case HTTP_RESPONSE.METHOD_NOT_ALLOWED:
                    Toast.error("当前method请求方式错误!")
                    return reject(data)
                default:
                    Toast.error("当前请求资源路径不存在!")
                    return reject(data)
            }
        }).catch(err => {
            if (loading) Toast.hide()
            Toast.error("当前请求资源路径不存在!")
            return reject(err)
        })
    })
}

/**
 * GET请求
 * @param url string
 * @param params object
 * @param options ApiOptions { loading?:boolean, title?:string, showToast?:boolean }
 */
export function get(url:string = '',params:object = {},options:ApiOptions = {}){
    return httpRequest(url,params,'GET',options)
}
/**
 * POST请求
 * @param url string
 * @param params object
 * @param options ApiOptions { loading?:boolean, title?:string, showToast?:boolean }
 */
export function post(url:string = '',params:object = {},options:ApiOptions = {}){
    return httpRequest(url,params,'POST',options)
}
